//
//  SeminarSendViewController.m
//  teachingliteApple
//
//  Created by admin on 15/9/25.
//  Copyright (c) 2015年 com.futian. All rights reserved.
//

#import "SeminarSendViewController.h"
#import "SeminarUrl.h"
//#import "JSONKit.h"
#import "util.h"
#import "BaseService.h"
#import "AFNetworking.h"

#define  kCompressionQuality  0.4
@interface SeminarSendViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
@property (strong, nonatomic) UIImage *image;

@end

@implementation SeminarSendViewController{
    int pictureTime;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置背景图片
//    [util setImageBackgroundWithImageView:_seminarSendBackgroundImageView];
    
//    pictureTime=0;
}

- (IBAction)seminar_send:(id)sender {
    
    NSString *title = [self.seminar_title.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *content = [self.seminar_content.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if ([Util isBlankString:title] || [Util isBlankString:content]) {
        [Util toastWithView:self.view.window AndText:CONTENT_TITLE_SPACE];
    }else{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *userId = [defaults objectForKey:USER_ID];
        NSString *courseId = [defaults objectForKey:COURSE_ID];
        NSString *parentId = IS_NULL;
        UIImage *image;
        
        if (self.seminar_imageView.image != nil&&pictureTime==1) {
            image = _seminar_imageView.image;
        }
        [self addSeminar:title :content :userId :courseId :parentId :image];
        
        
    }
}

- (IBAction)seminarPhotoAdd:(id)sender {
    self.deleteImageBtn.hidden = YES;//确保减号隐藏
    [self getPhoto];
}

#pragma mark - 打开photo
- (void)getPhoto{
    [self.seminar_title resignFirstResponder];
    [self.seminar_content resignFirstResponder];
    UIActionSheet *myActionSheet = [[UIActionSheet alloc]
                                    initWithTitle:nil
                                    delegate:self
                                    cancelButtonTitle:CANCEL
                                    destructiveButtonTitle:nil
                                    otherButtonTitles:PHOTO_CHOOSE , PHOTO_TAKE,nil];
    [myActionSheet showInView:self.view];

}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //从相册选择
            [self LocalPhoto];
            break;
        case 1:
            //拍照
            [self takePhoto];
            break;
        default:
            break;
    }
}


//从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
//    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
    } ];
    pictureTime=1;
}

//拍照
-(void)takePhoto{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
            
        } ];
    }else {
        NSLog(PHOTO_TAKE_TIPS);
    }
    pictureTime=1;
}


#pragma Delegate method UIImagePickerControllerDelegate
//图像选取器的委托方法，选完图片后回调该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    _image = image;
    //显示是否压缩图片
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:IS_COMPRESS message:nil delegate:self cancelButtonTitle:ORIGIN otherButtonTitles:COMPRESS , nil];
    [alertView show];
    
    //关闭相册界面
    [picker dismissModalViewControllerAnimated:YES];
    pictureTime=1;
}

#pragma mark - 是否图片压缩的对话框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    self.deleteImageBtn.hidden = NO;
    switch (buttonIndex) {
        case 0:
            _seminar_imageView.image = _image;
            _image = nil;//清空
            break;
        case 1:
            _seminar_imageView.image = [UIImage imageWithData:[Util imageWithImage:_image]];//清空

            break;
        default:
            break;
    }
}

#pragma mark - 从网络增加帖子
- (void)addSeminar : (NSString *)title :(NSString *)content :(NSString *)userId :(NSString *)courseId :(NSString *)parentId :(UIImage *)image {
    
    // AFHTTPSessionManager内部包装了NSURLSession
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    //请求参数
    NSDictionary *params =@{SEMINAR_TITLE:title, SEMINAR_CONTENT:content, USER_ID:userId, COURSE_ID:courseId, SEMINAR_ISFAVOURITE:COUNT_0};
    [sessionManager POST:ADD_SEMINAR_BY_FORM parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传图片
        if (image != nil) {
            [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1.0) name:FILE fileName:@".jpg" mimeType:@"image/jpeg"];
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        NSString *message = [responseObject objectForKey:MESSAGE];
        if ([message isEqualToString:SUCCESS] == YES) {
            //通知上一界面刷新
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:IS_YES forKey:IS_REFRESH];
            [defaults synchronize];
            [Util toastWithView:self.view.window AndText:SUCCESS_SEND];
            [self.navigationController popViewControllerAnimated:YES];

        } else{
            [Util toastWithView:self.view.window AndText:FAILE_SEND];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [Util  toastWithView:self.view.window AndText:ERROR];
        
    }];


}

#pragma mark - 退出键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self.seminar_title isExclusiveTouch] && ![self.seminar_content isExclusiveTouch]) {
        [self.seminar_title resignFirstResponder];
        [self.seminar_content resignFirstResponder];
    }
}


#pragma mark - 按DONE可以退出键盘
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}



#pragma mark - 限制title长度25
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *textString = textField.text ;
    NSUInteger length = [textString length];
    
    BOOL bChange =YES;
    if (length >= 25)
        bChange = NO;
    
    if (range.length == 1) {
        bChange = YES;
    }
    return bChange;
}


- (IBAction)deleteImage:(id)sender {
    self.seminar_imageView.image = nil;
    self.deleteImageBtn.hidden = YES;
}

@end
